#region using

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

#endregion

namespace RealEstate.Web
{
	public class CommandHandler : IHttpHandler
	{
		#region IHttpHandler Members

		public bool IsReusable
		{
			get { return true; }
		}

		public void ProcessRequest(HttpContext context)
		{
			// get the command name
			string strCommandName = System.IO.Path.GetFileNameWithoutExtension(context.Request.Path);

			// parse out the command path if there is any
			string strDiff = GetTrueRelativeURL(context);
			string strDomainName = Path.GetDirectoryName(strDiff);

			NameValueCollection requestParameters = context.Request.QueryString;

			//context.Response.Write("command name: " + strCommandName + "<br />");
			//context.Response.Write("diff: " + strDiff + "<br />");
			//context.Response.Write("domain name: " + strDomainName + "<br />");

			try
			{
				Dispatcher.Instance.Do(new Command(strDomainName, strCommandName, requestParameters));
			}
			catch (System.Threading.ThreadAbortException)
			{ 
				// for now do nothing
			}
			catch (Exception exp)
			{
				// need to do some logging
				throw exp;
			}
		}

		#endregion

		#region private methods
		
		private string GetTrueRelativeURL(HttpContext objContext)
		{
			string strAppPath = objContext.Request.ApplicationPath;
			string strRequestPath = objContext.Request.Path;

			strRequestPath = strRequestPath.ToLower();
			strAppPath = strAppPath.ToLower();

			int nLen = strAppPath.Length;
			if (strRequestPath.Substring(0, nLen) == strAppPath)
				return strRequestPath.Substring(nLen + 1);

			return strRequestPath;
		}

		#endregion

	}
}
